//
//  ZingBaseService.m
//  ZingMP3
//
//  Created by Mac on 11/14/12.
//  Copyright (c) 2012 NguyenTanThanh. All rights reserved.
//

#import "APIsBaseService.h"
#import "AFHTTPClient.h"
#import "NSError+Addition.h"
#import "AFJSONRequestOperation.h"
#import "JSON.h"
#import "AFURLConnectionOperation.h"
#import "AppDelegate.h"

#if kTestVersion
    #define API_Domain @"http://tele.mobile-solution.org/"
#else
    #define API_Domain @"https://wp-dot-erudite-stratum-347.appspot.com/"
#endif

@implementation APIsBaseService
@synthesize networkEngine;

- (id)init
{
    self = [super init];
    if (self) {
        self.networkEngine = [[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:API_Domain]] autorelease];
    }
    return self;
}

- (id)initWithDomain:(NSString *)domain {
    self = [super init];
    if (self) {
        self.networkEngine = [[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:domain]] autorelease];
    }
    return self;
}

+ (APIsBaseService *)service
{
    static APIsBaseService *baseService = nil;
    if (baseService == nil) {
        baseService = [[APIsBaseService alloc]init];
    }
    return baseService;
}

/*----------------------------------------------------------------------------
 Method: requestWithURL: params: successBlock: errorBlock: httpMethod:
 called to get data with path and params.
 -----------------------------------------------------------------------------*/
- (void)requestWithURL:(NSString*)urlString
                params:(NSMutableDictionary*)params
          successBlock:(void (^)(NSDictionary *))successBlock
            errorBlock:(void (^)(NSError *))errorBlock
            httpMethod:(NSString *)method{
    if ([[method uppercaseString] isEqualToString:@"GET"]) {
        [self.networkEngine getPath:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
//            NSLog(@"=====API LOG=====");
            NSLog(@"request: %@", operation.request);
//            NSLog(@"params: %@", params);
//            NSLog(@"response: %@", operation.responseString);
//            NSLog(@"==========");
             SBJsonParser *jsonParser  =[[[SBJsonParser alloc] init] autorelease];
             NSDictionary *response = [jsonParser objectWithString:operation.responseString];
//            NSDictionary *response = [operation.responseString objectFromJSONString];
            if ([response isKindOfClass:[NSDictionary class]]) {
                int statusCode = [[response objectForKey:@"error"] intValue];
                if (statusCode == 0) {
                    /* call success block */
                    successBlock(response);
                } else {
                    NSDictionary *bodyDic = [response objectForKey:@"body"];
                    if ([bodyDic isKindOfClass:[NSDictionary class]]) {
                        NSString *errorCode = [bodyDic objectForKey:@"error_code"];
                        NSString *description = [bodyDic objectForKey:@"error_message"];
                        NSError *error = [NSError errorWithCode:[errorCode intValue] description:description];
                        errorBlock(error);
                    } else {
                        NSString *message = @"Our server is under construction.\n Please try again later.";
                        if ([response objectForKey:@"message"]) {
                            message = [response objectForKey:@"message"];
                        }
                        
                        NSError *error = [NSError errorWithCode:0 description:message];
                        errorBlock(error);
                    }
                    
                }
            } else {
                if ([response isKindOfClass:[NSArray class]]) {
                    NSMutableDictionary *dictionanry = [NSMutableDictionary dictionary];
                    [dictionanry setObject:response forKey:@"docs"];
                    successBlock(dictionanry);
                }
                else
                {
                    NSString *message = @"Our server is under construction.\n Please try again later.";
                    NSError *error = [NSError errorWithCode:0 description:message];
                    errorBlock(error);
                }
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Response for:%@\n==================\n%@\n==================", [NSString stringWithFormat:@"%@/%@", @"", urlString], [error localizedDescription]);
            NSError *gntError = [NSError errorWithCode:[error code] description:[error localizedDescription]];
            errorBlock(gntError);
        }];
        
    } else {
        [self.networkEngine postPath:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
            
            SBJsonParser *jsonParser  =[[[SBJsonParser alloc] init] autorelease];
            NSDictionary *response = [jsonParser objectWithString:operation.responseString];
//            NSDictionary *response = [operation.responseString objectFromJSONString];
            if ([response isKindOfClass:[NSDictionary class]]) {
                int statusCode = [[response objectForKey:@"error"] intValue];
                if (statusCode == 0) {
                    /* call success block */
                    successBlock(response);
                } else {
                    NSDictionary *bodyDic = [response objectForKey:@"body"];
                    if ([bodyDic isKindOfClass:[NSDictionary class]]) {
                        NSString *errorCode = [bodyDic objectForKey:@"error_code"];
                        NSString *description = [bodyDic objectForKey:@"error_message"];
                        NSError *error = [NSError errorWithCode:[errorCode intValue] description:description];                        
                        errorBlock(error);
                    } else {
                        NSString *message = @"Our server is under construction.\n Please try again later.";
                        if ([response objectForKey:@"message"]) {
                            message = [response objectForKey:@"message"];
                        }
                        
                        NSError *error = [NSError errorWithCode:0 description:message];
                        errorBlock(error);
                    }
                    
                }
            } else {
                NSString *message = @"Our server is under construction.\n Please try again later.";
                NSError *error = [NSError errorWithCode:0 description:message];
                errorBlock(error);
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Response for:%@\n==================\n%@\n==================", [NSString stringWithFormat:@"%@/%@", @"API", urlString], [error localizedDescription]);
            NSError *gntError = [NSError errorWithCode:[error code] description:[error localizedDescription]];
            errorBlock(gntError);
        }];
    }
}

- (void)dealloc {
    self.networkEngine = nil;
    [super dealloc];
}


- (void)showAlertFail{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert !" message:@"An unknown error has occurred, there might be problems with the data format from our server. Please try again in few seconds." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    alert.tag = 199;
    [alert show];
    [alert release];
}

@end
